package com.gzdh.tang.ali.rule;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.ali.model.OuterExtends;
import com.gzdh.tang.comm.constant.SpringContextUtils;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.mobile.entity.Kl;
import com.gzdh.tang.mobile.service.KlService;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.DateUtil;
import com.gzdh.tang.warehouse.service.DeviceService;
import com.gzdh.tang.warehouse.service.InStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
public class AliZheKouRule2 implements IPayRuleHandler {
    FkService fkService;

    GsService gsService;

    MacMainpSbruanService macMainpSbruanService;

    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    MacMainpSbruanKlService macMainpSbruanKlService;

    ReserveService reserveService;

    TangDeviceService tangDeviceService;

    DeviceService deviceService;

    InStockService inStockService;

    MacMainpSbruanKlDinnerService macMainpSbruanKlDinnerService;

    MacMainpSbruanKlButieService macMainpSbruanKlButieService;

    KlService klService;

    TangAddrService tangAddrService;

    ReserveXfjTempService reserveXfjTempService;


    public AliZheKouRule2() {
        fkService = (FkService) SpringContextUtils.getBean("fkServiceImpl");
        gsService = (GsService) SpringContextUtils.getBean("gsService");
        macMainpSbruanService = (MacMainpSbruanService) SpringContextUtils.getBean("macMainpSbruanService");
        macMainpSbruanDinnerService = (MacMainpSbruanDinnerService) SpringContextUtils.getBean("macMainpSbruanDinnerService");
        macMainpSbruanKlService = (MacMainpSbruanKlService) SpringContextUtils.getBean("macMainpSbruanKlService");
        reserveService = (ReserveService) SpringContextUtils.getBean("reserveService");
        tangDeviceService = (TangDeviceService) SpringContextUtils.getBean("tangDeviceServiceImpl");
        deviceService = (DeviceService) SpringContextUtils.getBean("deviceServiceImpl");
        inStockService = (InStockService) SpringContextUtils.getBean("inStockService");
        macMainpSbruanKlDinnerService = (MacMainpSbruanKlDinnerService) SpringContextUtils.getBean("macMainpSbruanKlPriceService");
        macMainpSbruanKlButieService = (MacMainpSbruanKlButieService) SpringContextUtils.getBean("macMainpSbruanKlButieService");
        klService = (KlService) SpringContextUtils.getBean("klService");
        tangAddrService = (TangAddrService) SpringContextUtils.getBean("tangAddrServiceImpl");
        reserveXfjTempService = (ReserveXfjTempService) SpringContextUtils.getBean("reserveServiceXfjTemp");
    }

    @Override
    public JSONObject toCardPay(JSONObject params) throws RuntimeException {
        //缺省支付，默认插入到reserve即可操作
        String deviceId = params.getString("deviceId");
        String price = params.getString("price");
        String cardsn = params.getString("auth");
        String orders = params.getString("orders");
        int onLine = params.getInteger("onLine");
        Date date = new Date();

        String dateStr = params.getString("dateStr");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        try {
            if (onLine > 0) {
                try {
                    date = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(dateStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
            if (fk == null) {
                throw new RuntimeException("非法卡");
            }
            Kl kl = klService.getOne(new QueryWrapper<Kl>().lambda().eq(Kl::getBm, fk.getKl()));
            if (kl != null && kl.getValid() == 1) {
                //判断有效期
                if (fk.getValiddate().compareTo(new Date()) < 0) {
                    throw new RuntimeException("超过有效期");
                }
            }
            jsonObject.put("fk", fk);
            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>()
                    .lambda().eq(MacMainpSbruan::getMac, deviceId));
            try {
                String dinner = getDinner(macMainpSbruan).trim();
                macMainpSbruan.setDinner(dinner);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("餐次获取失败");
            }
            List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId,
                    macMainpSbruan.getId()));
            if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
                throw new RuntimeException("不支持此卡类");
            }
            MacMainpSbruanKlButie macMainpSbruanKlButie = macMainpSbruanKlButieService.getOne(new QueryWrapper<MacMainpSbruanKlButie>()
                    .lambda().eq(MacMainpSbruanKlButie::getDinner, macMainpSbruan.getDinner())
                    .eq(MacMainpSbruanKlButie::getKl, fk.getKl()));

            if (macMainpSbruanKlButie == null) {
                throw new RuntimeException("优惠有误请设置");
            }
            int count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
            if (count > 0) {
                throw new RuntimeException("此卡已挂失,请回收");
            }
            JSONObject priceRule = judgYouhui(macMainpSbruanKlButie, price);
            Fk fk1 = cardToReserve2(deviceId, new BigDecimal(priceRule.getString("aPrice")).multiply(new BigDecimal(100)).intValue(),
                    orders, macMainpSbruan, macMainpSbruanKlButie.getButie(), fk, priceRule, onLine, date);
            jsonObject.put("fk", fk1);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", priceRule.getString("aPrice"));
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("原消费金额", price));
            outerExtendsList.add(addOutOuterExtends("优惠金额", priceRule.getString("yPrice")));
            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    private OuterExtends addOutOuterExtends(String name, String value) {
        OuterExtends outerExtends = new OuterExtends();
        outerExtends.setTitle(name);
        outerExtends.addDetail(name, value);
        return outerExtends;
    }

    @Override
    public JSONObject toCashPay(JSONObject params) throws RuntimeException {
        return null;
    }


    public JSONObject dzkPay(JSONObject params) {
        String authStr = params.getString("auth");
        byte[] bytes = Base64.getDecoder().decode(authStr);
        String json = new String(bytes);
        String cardno = json.split(",")[0].split("=")[1];
        String dates = json.split(",")[2].split("=")[1];
        String price = params.getString("price");
        String orders = params.getString("orders");
        String deviceId = params.getString("deviceId");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        try {
            String nowDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis() - (2 * (60 * 1000) * 60)));
            if (new BigDecimal(nowDate).compareTo(new BigDecimal(dates)) > 0) {
                throw new RuntimeException("二维码已过期");
            }
            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, cardno));
            jsonObject.put("fk", fk);
            Kl kl = klService.getOne(new QueryWrapper<Kl>().lambda().eq(Kl::getBm, fk.getKl()));
            if (kl != null && kl.getValid() == 1) {
                //判断有效期
                if (fk.getValiddate().compareTo(new Date()) < 0) {
                    throw new RuntimeException("超过有效期");
                }
            }
            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
            try {
                String dinner = getDinner(macMainpSbruan).trim();
                macMainpSbruan.setDinner(dinner);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("餐次获取失败");
            }
            List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId,
                    macMainpSbruan.getId()));
            if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
                throw new RuntimeException("不支持此卡类");
            }
            MacMainpSbruanKlButie macMainpSbruanKlButie = macMainpSbruanKlButieService.getOne(new QueryWrapper<MacMainpSbruanKlButie>()
                    .lambda().eq(MacMainpSbruanKlButie::getDinner, macMainpSbruan.getDinner())
                    .eq(MacMainpSbruanKlButie::getKl, fk.getKl()));

            if (macMainpSbruanKlButie == null) {
                throw new RuntimeException("优惠有误请设置");
            }
            JSONObject priceRule = judgYouhui(macMainpSbruanKlButie, price);
            if (reserveService.payCounts(fk.getCardno(), macMainpSbruan.getDinner()) > 0) {
                priceRule = new JSONObject();
                priceRule.put("aPrice", price);//优惠后的支付金额
                priceRule.put("price", price);//原金额
                priceRule.put("yPrice", "0");//优惠的金额
            }

            Fk fk1 = cardToReserve2(deviceId, new BigDecimal(priceRule.getString("aPrice")).multiply(new BigDecimal(100)).intValue(),
                    orders, macMainpSbruan, macMainpSbruanKlButie.getButie(), fk, priceRule, 0, new Date());

            jsonObject.put("fk", fk);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", priceRule.getString("aPrice"));
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("原消费金额", price));
            outerExtendsList.add(addOutOuterExtends("优惠金额", priceRule.getString("yPrice")));
            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }


    @Override
    public JSONObject toQrPay(JSONObject params) throws RuntimeException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        //授权码，付款码或者电子饭卡
        String auth = params.getString("auth");
        int authType = 0;
        if (auth.length() < 19 && "1".equals(auth.substring(0, 1))) {
            //微信
            jsonObject.putAll(weixinQrPay(params));
        } else if (auth.length() < 19 && "2".equals(auth.substring(0, 1))) {
            //支付宝
            jsonObject.putAll(aliQrPay(params));
        } else {
            //其他，需要解码
            jsonObject.putAll(dzkPay(params));
        }
        return jsonObject;
    }

    public JSONObject aliQrPay(JSONObject params) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", false);
        jsonObject.put("msg", "请使用电子饭卡");
        return jsonObject;
    }

    public JSONObject weixinQrPay(JSONObject params) {
        JSONObject jsonObject = new JSONObject();
        String price = params.getString("price");
        price = new BigDecimal(price).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        String orders = params.getString("orders");
        String auth = params.getString("auth");
        String deviceId = params.getString("deviceId");
        jsonObject.put("success", false);
        jsonObject.put("msg", "请使用电子饭卡");
        return jsonObject;
    }

    @Override
    public JSONObject toFacePay(JSONObject params) throws RuntimeException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String deviceId = params.getString("deviceId");
        String price = params.getString("price");
        String authCode = params.getString("faceToken");
        String orders = sdf.format(new Date()) + deviceId.substring(deviceId.length() - 5);
        String aliUid = params.getString("aliUid");
        String terminalParams = params.getString("terminal_params");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getAliUserId, aliUid));

        String enterprisePayAmount = "0.00";
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        orders += String.format("%04d", macMainpSbruan.getAddr());
        try {
            Addr addr = tangAddrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, macMainpSbruan.getAddr()));

            if (fk == null) {
                throw new RuntimeException("查无此人");
            }
            if (StringUtils.isEmpty(fk.getAliEmployeeId())) {
                throw new RuntimeException("请先绑定企业");
            }
            MacMainpSbruanKlButie macMainpSbruanKlButie = macMainpSbruanKlButieService.getOne(new QueryWrapper<MacMainpSbruanKlButie>()
                    .lambda().eq(MacMainpSbruanKlButie::getDinner, macMainpSbruan.getDinner())
                    .eq(MacMainpSbruanKlButie::getKl, fk.getKl()));

            if (macMainpSbruanKlButie == null) {
                throw new RuntimeException("优惠有误请设置");
            }
            JSONObject priceRule = judgYouhui(macMainpSbruanKlButie, price);
            if (reserveService.payCounts(fk.getCardno(), macMainpSbruan.getDinner()) > 0) {
                priceRule = new JSONObject();
                priceRule.put("aPrice", price);//优惠后的支付金额
                priceRule.put("price", price);//原金额
                priceRule.put("yPrice", "0");//优惠的金额
            }

            price = priceRule.getString("aPrice");

//            if (new BigDecimal(fk.getBtye()).compareTo(new BigDecimal(price)) >= 0 ||
//                    new BigDecimal(fk.getKye()).compareTo(new BigDecimal(price)) >= 0) {
//                enterprisePayAmount = price;
//            }
            Map<String, Object> resMap = reserveXfjTempService.toCardPay2(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk,
                    orders, 1, new Date(), null);
            Fk fk1 = (Fk) resMap.get("fk");
            enterprisePayAmount = resMap.get("amount").toString();
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
                    "json", "GBK", AliPayUtil.getPublicKey(),
                    "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean = new JsonsRootBean(orders, price,
                    authCode, AliPayUtil.getAssignJointAccountId(), enterprisePayAmount, terminalParams);
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, addr.getAliAppAuthToken());
            log.info(JSONObject.toJSONString(response));
            if (!response.isSuccess()) {
                throw new RuntimeException("支付失败");
            }
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("消费金额", price));
            if (response.getEnterprisePayInfo().getIsUseEnterprisePay()) {
                List<ReserveXfjTemp> reserveXfjTempList = reserveXfjTempService.list(
                        new QueryWrapper<ReserveXfjTemp>().lambda().eq(ReserveXfjTemp::getLsh2, orders)
                );
                List<Reserve> reserveList = new ArrayList<>();
                for (ReserveXfjTemp goo : reserveXfjTempList) {
                    Reserve reserve = new Reserve();
                    BeanUtils.copyProperties(goo, reserve);
                    reserveList.add(reserve);
                }
                reserveService.saveBatch(reserveList);


            } else {
                //未使用企业付，扣支付宝费用
                insertReserve(deviceId, orders,
                        new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(),
                        new BigDecimal(price), "4", macMainpSbruanKlButie.getButie(), orders, priceRule, new Date());
            }
            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
            jsonObject.put("fk", fk);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", price);
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    private Fk cardToReserve2(String deviceId, int price, String reqSeqNo, MacMainpSbruan macMainpSbruan,
                              String zkl, Fk fk, JSONObject priceRule, int type, Date date) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal xfPrice2 = new BigDecimal(price).divide(new BigDecimal(100));
        if (type <= 0) {
            if (xfPrice.compareTo(new BigDecimal(fk.getKye()).add(new BigDecimal(fk.getBtye()))) > 0) {
                throw new RuntimeException("余额不足");
            }
            int count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
            if (count > 0) {
                throw new RuntimeException("此卡已挂失,请回收");
            }
        }
        if (price == 0) {
            throw new RuntimeException("金额异常，请重新输入");
        }
        String sc = "0";
        BigDecimal cardPrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        if (btye.compareTo(new BigDecimal(0)) > 0) {
            sc = "1";
            cardPrice = btye;
            if (btye.compareTo(xfPrice) <= 0) {
                xfPrice = btye;
                fk.setBtye("0");
            } else {
                fk.setBtye(btye.subtract(xfPrice).toPlainString());
            }
        } else {
            cardPrice = kye;
            fk.setKye(kye.subtract(xfPrice).toPlainString());
        }
        int counts = reserveService.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo))
                .eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan,
                    "现金菜", macMainpSbruan.getCode(), cardPrice, sc, zkl, String.valueOf(reqSeqNo), priceRule, date);
        }
        xfPrice = xfPrice2.subtract(xfPrice);
        if ("1".equals(sc) && xfPrice.compareTo(new BigDecimal(0)) > 0) {
            sc = "0";
            cardPrice = kye;
            date = new Date(date.getTime() + 100);
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan,
                    "现金菜", macMainpSbruan.getCode(), cardPrice, sc, zkl, String.valueOf(reqSeqNo), priceRule, date);

            fk.setKye(kye.subtract(xfPrice).toPlainString());
        }
        return fk;
    }

    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService
                .list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该灶类");
    }

    private boolean judeKl(List<MacMainpSbruanKl> macMainpSbruanKlList, String kl) {
        for (MacMainpSbruanKl goo : macMainpSbruanKlList) {
            if (goo.getKl().equals(kl.trim())) {
                return true;
            }
        }
        return false;
    }

    private JSONObject judgYouhui(MacMainpSbruanKlButie macMainpSbruanKlButie, String priceStr) {
        BigDecimal price = new BigDecimal(priceStr);
        JSONObject jsonObject = new JSONObject();
        if (macMainpSbruanKlButie.getType() == 2) {
            //折扣比例
            //优惠后金额
            BigDecimal affPrice = price.multiply((new BigDecimal(macMainpSbruanKlButie.getButie())
                    .divide(new BigDecimal(100))));
            jsonObject.put("aPrice", affPrice.toPlainString());
            jsonObject.put("price", priceStr);
            jsonObject.put("yPrice", price.subtract(affPrice));
        } else if (macMainpSbruanKlButie.getType() == 1) {
            BigDecimal affPrice = price.subtract((new BigDecimal(macMainpSbruanKlButie.getButie())));
            jsonObject.put("aPrice", affPrice.toPlainString());//优惠后的支付金额
            jsonObject.put("price", priceStr);//原金额
            jsonObject.put("yPrice", price.subtract(affPrice));//优惠的金额
        }
        try {
            JSONObject restrictionsJson = JSONObject.parseObject(macMainpSbruanKlButie.getRestrictions());
            String minPrice = restrictionsJson.getString("minPrice");
            String maxPrice = restrictionsJson.getString("maxPrice");
            if (price.compareTo(new BigDecimal(minPrice)) < 0 ||
                    price.compareTo(new BigDecimal(maxPrice)) > 0) {
                jsonObject.put("aPrice", priceStr);//优惠后的金额
                jsonObject.put("price", priceStr);//原金额
                jsonObject.put("yPrice", "0");//优惠的金额
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    public boolean insertReserve(String rgTermSN, String reqSeqNo, int price,
                                 int sl, Fk fk, MacMainpSbruan macMainpSbruan,
                                 String hName, String code, BigDecimal cardPrice,
                                 String sc,
                                 String zkl, String orders, JSONObject priceRule,
                                 Date date) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal yePrice = new BigDecimal(0);
        String zkls = "100";
        try {
            zkls = new BigDecimal(priceRule.getString("aPrice"))
                    .divide(new BigDecimal(priceRule.getString("price")), 2, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            log.error("错误", e);
            e.printStackTrace();
        }
        yePrice = cardPrice.subtract(xfPrice);
        Reserve reserve = new Reserve();
        reserve.setZkl(zkls);
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(macMainpSbruan.getBqh());
        reserve.setKsh(macMainpSbruan.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(code);
        reserve.setSl(sl);
        reserve.setStatus("1");
        reserve.setDiscountAmount(priceRule.getString("yPrice"));
        reserve.setOriginalAmount(priceRule.getString("price"));
        reserve.setJe((new BigDecimal(price).multiply(new BigDecimal(sl))).divide(new BigDecimal(100)).toPlainString());
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {

            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname(hName);
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setOpenid(fk.getCardsn());
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(orders);
        reserve.setAddr(macMainpSbruan.getAddr());
        reserveService.save(reserve);
        return true;
    }
}
